import java.util.Random;
import java.util.Scanner;
import java.io.*;

/**
 * Game class Responsibilities set up game and control the flow of the game
 * 
 * @author kkopiec
 * 
 */
public class Game {
	static private int numPlayers;
	static private Player[] player;
	@SuppressWarnings("unused")
	static private Display display;
	@SuppressWarnings("unused")
	static private Board board;
	@SuppressWarnings("unused")
	static private Bag bag;
	static private Dictionary dictionary;
	static private Random rand = new Random();
	static public boolean running = true;
	static protected int currentPlayerCycle;
	static protected int numOfPasses = 0;
	static protected Topten hsList = null;
	static protected File hsFile;

	public Game() {

		display = new Display();
		board = new Board();
		bag = new Bag();
		dictionary = new Dictionary();
		hsFile = new File("hs.data");

		if (hsFile.exists()) {
			FileInputStream fis = null;
			ObjectInputStream in = null;
			try {
				fis = new FileInputStream(hsFile);
				in = new ObjectInputStream(fis);
				hsList = (Topten) in.readObject();
				in.close();
			} catch (IOException e) {
				System.out.println("Top Scores not found");
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			hsList = new Topten();
		}

		menu();

	}

	public static void menu(){
		System.out.println("Please Select an option");		// Add to game class when created
		System.out.println("1. Start New Game");
		System.out.println("2. Highscores");			// Add getters and setters?
		System.out.println("3. Quit");
		System.out.print("Enter Your Option: ");
		Scanner input = new Scanner(System.in);
		int option = input.nextInt();
		
		switch(option){
		case 1:
			System.out.println("Number of players: ");
			numPlayers = input.nextInt();
			player = new Player[numPlayers];
			for ( int i = 0 ; i < numPlayers ; i++){
				player[i] = new Player(i);
			}
			currentPlayerCycle = rand.nextInt(numPlayers);
			while(running && numOfPasses != 3){
				
				Display.refresh();
				
				if (player[currentPlayerCycle%numPlayers].takeTurn() == false){
					numOfPasses++;
					Display.displayNotification(player[currentPlayerCycle%numPlayers].name + ": PASS  --> " + numOfPasses + " consequent passes");
				}
				else {
					numOfPasses = 0;
					if (Bag.isEmpty() && player[currentPlayerCycle-1%numPlayers].getNumOfTiles() == 0) endGame(currentPlayerCycle-1%numPlayers);
				}
				currentPlayerCycle++;
				
			}
			endGame(-1);
			menu();
			break;
		
		
		case 2:
			//System.out.println("Not implemented yet.");
			for (String e:hsList.getTopTen()){
				System.out.println(e);
			}
			menu();
		case 3:
			System.out.println("Usage:");
			System.out.println("Commands during play:");
			System.out.println("e2 r word - put word at e 2 direction right");
			System.out.println("e2 d word - put word at e 2 direction down");
			System.out.println("e2 r w[o]r[d] - put word at e 2 direction right, tiles o and d are already on the board so no need to put them there");
			System.out.println("ex wxft - exchange tiles w,x,f and t");
			System.out.println(("ch word - chellange given word from last setup"));
			System.out.println("p - pass");
			System.out.println("q - quit to the menu without finnishing game");
			menu();
		case 4:
			break;
		}
	}

	public static void passMsg(String s) {
		Display.displayNotification(s);
	}

	public static void main(String[] arc0) {
		@SuppressWarnings("unused")
		Game g = new Game();

	}

	public static void challengeLast(String wtc) {
		Setup lastSetup = Board.lastSetup();
		if (lastSetup.canChellange(wtc)) {
			if (dictionary.check(wtc)) {
				Display.displayNotification("Chellange of \"" + wtc
						+ "\" unsuccesfull");
				Board.fixBoard(true);
			} else {
				Display.displayNotification("Chellange of \"" + wtc
						+ "\" succesfull");
				Board.fixBoard(false);

				player[(--currentPlayerCycle) % numPlayers]
						.updateScore(lastSetup.getScore());
				// currentPlayerCycle--;
			}
		} else {
			Display.displayNotification("Chellange of \"" + wtc
					+ "\" unsuccesfull");
			Board.fixBoard(true);
		}
	}

	public static String getScores() {
		String scores = "";
		for (int i = 0; i < numPlayers; i++) {
			scores += "-{" + player[i].name + ": " + player[i].score + "}-+";
		}
		return scores;
	}

	public static void endGame(int pNo) {
		running = false;
		int highestScore = 0;
		int winningPlayer = 0;

		int sumOfRemainingTiles = 0;
		for (int i = 0; i < numPlayers; i++) {
			hsList.add(player[i].name, player[i].getScore());
			if (player[i].getScore() > highestScore) {
				highestScore = player[i].getScore();
				winningPlayer = i;

				
				}
			for (Tile e : player[i].rack) {
				sumOfRemainingTiles += e.value;
			}

		}
		if (pNo >= 0) {
			player[pNo].score += sumOfRemainingTiles;
			winningPlayer = player[pNo].getScore() > highestScore ? pNo
					: winningPlayer;
		}
		Board.wipeBoard();
		Board.displayOnBoard("Game Over", Board.Position.CENTER, 1);
		Board.displayOnBoard("Winner is :", Board.Position.LEFT, 3);
		Board.displayOnBoard(player[winningPlayer].name + ": "
				+ player[winningPlayer].getScore(), Board.Position.CENTER, 5);
		Display.refresh();
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		try {
			fos = new FileOutputStream(hsFile);
			out = new ObjectOutputStream(fos);
			out.writeObject(hsList);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
